import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import { NumberFormat2 } from '@/utils';
import emitter from '#/utils/events';
import { option } from './helper';
import styles from './index.less';

let myChart = null;
export default function echartsBar({ capData = [], dataList = [], setDataFn, isEdit, check }) {
  const data = dataList.map((v) => {
    return v?.fixedValue;
  });
  let bruchSeat = [];
  const EChartsRef = useRef(null);
  const [result, setResult] = useState([]);

  useEffect(() => {
    emitter.addListener('onChangeMnue', resizeMenu);
    window.addEventListener('resize', resizeMenu);
    return () => {
      window.removeEventListener('resize', resizeMenu);
      emitter.removeListener('onChangeMnue', resizeMenu);
    };
  }, []);

  useEffect(async () => {
    await chartOption();
    isEdit && setTimeout(ondragendFun, 0);
  }, [JSON.stringify(data), check]);

  const checkBruchFn = () => {
    if (check) {
      myChart &&
        myChart.dispatchAction({
          type: 'takeGlobalCursor',
          key: 'brush',
          brushOption: { brushType: 'lineX' },
        });
    } else {
      myChart &&
        myChart.dispatchAction({
          type: 'takeGlobalCursor',
          key: 'brush',
          brushOption: { brushType: false },
        });
    }
  };

  const chartOption = () => {
    myChart = echarts.getInstanceByDom(EChartsRef?.current) || echarts.init(EChartsRef?.current);
    myChart && myChart.setOption(option(data, toolTipFn, capData, false), true);
    if (isEdit) {
      myChart.off('brushEnd');
      myChart.on('brushEnd', (val) => {
        let seat = val.areas?.[0]?.range;
        if (seat?.[0]?.[0] > seat?.[0]?.[1]) {
          seat[0]?.reverse();
          seat[1]?.reverse();
        }
        bruchSeatFun(seat);
      });
    }
    // 鼠标放上去的效果  加粗线
    myChart.on('mouseover', function (params) {
      myChart.setOption({ series: { name: params.seriesName, lineStyle: { width: 2 } } });
    });
    myChart.on('mouseout', function (params) {
      myChart.setOption({ series: { name: params.seriesName, lineStyle: { width: 1 } } });
    });

    myChart.dispatchAction({
      type: 'showTip',
      seriesIndex: 0,
      dataIndex: 0,
    });
  };

  function bruchSeatFun(location) {
    const x1 = location[0];
    const x2 = location[1];
    const indArr = [];
    data.forEach((item, ind) => {
      const bruchSeat = myChart.convertToPixel('grid', [ind, item]);
      if (x1 <= bruchSeat[0] && bruchSeat[0] <= x2) {
        indArr.push(ind);
      }
    });
    bruchSeat = indArr;
    ondragendFun();
  }

  function ondragendFun() {
    const styleData = data.map((v, i) => {
      if (bruchSeat.includes(i)) {
        return { value: v, symbolSize: 12 };
      }
      return { value: v };
    });
    myChart &&
      myChart.setOption({
        ...option(styleData, toolTipFn, capData),
        graphic: echarts.util.map(data, function (dataItem, dataIndex) {
          return {
            type: 'circle',
            shape: { r: 10 / 2 },
            position: myChart.convertToPixel('grid', [dataIndex, dataItem]),
            invisible: true,
            draggable: true,
            ondrag: function () {
              onPointDragging(dataIndex, [this.x, this.y]);
            },
            ondragend: function () {
              // bruchFun();
              setDataFn(dataList.map((v, i) => ({ ...v, fixedValue: data?.[i] })));
              bruchSeat = [];
              ondragendFun(data);
              checkBruchFn();
            },
            z: 10,
          };
        }),
      });
    checkBruchFn();
  }
  function onPointDragging(dataIndex, pos) {
    const _data = data;
    const changData = myChart.convertFromPixel('grid', pos)[1];
    const diffNum = (changData - _data?.[dataIndex] || 0) * 1;

    if (capData[0] <= changData) {
      _data[dataIndex] = capData[0];
    } else if (changData <= 0) {
      _data[dataIndex] = 0;
    } else {
      _data[dataIndex] = changData;
    }

    if (bruchSeat.includes(dataIndex)) {
      bruchSeat.forEach((v) => {
        if (v !== dataIndex) {
          if (capData[0] <= _data[v] * 1 + diffNum) {
            _data[v] = capData[0];
          } else if (_data[v] * 1 + diffNum <= 0) {
            _data[v] = 0;
          } else _data[v] = _data[v] * 1 + diffNum;
        }
      });
    }
    ondragendFun();
  }

  const resizeMenu = () => {
    setTimeout(() => {
      myChart?.resize();
    }, 500);
  };
  const toolTipFn = (val) => {
    setResult(val);
  };

  return (
    <div style={{ width: '100%', height: '100%' }} id="ahClickAway">
      <div className={styles.tooltip}>
        {result?.[0]?.axisValue}
        {result.map((item, index) => {
          return (
            <span key={index} style={{ marginLeft: '12px', fontSize: '12px' }}>
              {item?.seriesName}:
              <font style={{ color: item?.borderColor || '', margin: '5px' }}>
                {NumberFormat2(item?.value, 3)}
              </font>
            </span>
          );
        })}
      </div>
      <div ref={EChartsRef} style={{ width: '100%', height: '100%' }} />
    </div>
  );
}
